package com.example.ai.mapper;

import com.example.ai.entity.ChatMessage;
import com.example.ai.entity.ChatSession;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface ChatHistoryMapper {

    /**
     * 创建新会话
     *
     * @param session
     * @return
     */
    @Insert("INSERT INTO chat_session (session_id, user_id, title) " +
            "VALUES (#{sessionId}, #{userId}, #{title})")
    int createSession(ChatSession session);

    /**
     * 插入消息
     *
     * @param message
     * @return
     */
    @Insert("INSERT INTO chat_message (session_id, role, content, tokens) " +
            "VALUES (#{sessionId}, #{role}, #{content}, #{tokens})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insertMessage(ChatMessage message);

    /**
     * 查询会话列表（分页）
     *
     * @param userId
     * @param offset
     * @param pageSize
     * @return
     */
    @Select("SELECT * FROM chat_session WHERE user_id = #{userId} " +
            "ORDER BY update_time DESC LIMIT #{offset}, #{pageSize}")
    List<ChatSession> selectSessions(@Param("userId") String userId,
                                     @Param("offset") int offset,
                                     @Param("pageSize") int pageSize);

    /**
     * 查询会话详情（带消息）
     *
     * @param sessionId
     * @return
     */
    @Select("SELECT * FROM chat_message WHERE session_id = #{sessionId} " +
            "ORDER BY create_time ASC")
    List<ChatMessage> selectMessages(String sessionId);

    /**
     * 删除会话
     *
     * @param sessionId
     * @return
     */
    @Delete("DELETE FROM chat_session WHERE session_id = #{sessionId}")
    int deleteSession(String sessionId);

    /**
     * 更新修改时间
     *
     * @param sessionId
     * @return
     */
    @Update("UPDATE chat_session SET update_time = NOW() WHERE session_id = #{sessionId}")
    int updateSessionTime(String sessionId);

}
